package com.reset.password.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.reset.password.entity.User;
import com.reset.password.entity.dto.UserDTO;
import com.reset.password.entity.dto.UserRegisterDTO;
import com.reset.password.entity.vo.UserVO;
import com.reset.password.mapper.UserMapper;
import com.reset.password.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reset.password.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mr.Abel
 * @since 2024-11-05
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public UserVO login(String email, String password) {
           User userEmail =  baseMapper.findByEmail(email);
           if (userEmail == null) {
               return null;
           }
           if (!userEmail.getPassword().equals(password)) {
               return null;
           }
           UserVO userVO = new UserVO();
           BeanUtils.copyProperties(userEmail, userVO);
           return userVO;
    }

    @Override
    public UserVO register(UserRegisterDTO user) {
        if (baseMapper.findByEmail(user.getEmail()) == null) {
            User user1 = new User();
            String[] saltAndPassword = PasswordUtil.encrypt(user.getPassword());
            user1.setSalt(saltAndPassword[0]);
            user.setPassword(saltAndPassword[1]);
            BeanUtils.copyProperties(user, user1);
            int i = baseMapper.insert(user1);
            if (i > 0) {
                User userEmail = baseMapper.findByEmail(user.getEmail());
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(userEmail, userVO);
                return userVO;
            }
        }
        return null;
    }
    @Override
    public boolean updatePassword(UserDTO user) {
        User selectUser = baseMapper.findByEmail(user.getEmail());
        String password = PasswordUtil.decrypt(user.getPassword(), selectUser.getSalt());
        int  i = baseMapper.updatePassword(user.getEmail(),password);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public UserVO findByEmail(String email) {
        UserVO user = new UserVO();
        User user1 = baseMapper.findByEmail(email);
        BeanUtils.copyProperties(user1, user);
        return user;
    }
}
